//
//  FormCellView.m
//  etionUI
//
//  Created by wangjian on 12/23/13.
//  Copyright (c) 2013 GuangZhouXuanWu. All rights reserved.
//

#import "FormCellView.h"

#define FORMVIEW_MAX_IMAGE_VIEW_SIZE 50

/**
 *  CFormCellIndex
 */

@implementation CFormCellIndex

+ (CFormCellIndex *)indexWithtRow:(NSUInteger)row col:(NSUInteger)col
{
    CFormCellIndex *index = [[[CFormCellIndex alloc] initWithtRow:row col:col] autorelease];
    return index;
}

- (id)copyWithZone:(NSZone *)zone
{
    CFormCellIndex *index = [[self class] allocWithZone:zone];
    
    index.row = self.row;
    index.col = self.col;
    
    return index;
}

- (id)initWithtRow:(NSUInteger)row col:(NSUInteger)col
{
    if (self = [super init])
    {
        self.row = row;
        self.col = col;
    }
    return self;
}

- (BOOL)isEqualToIndex:(CFormCellIndex *)index
{
    if (index != nil && self.row==index.row && self.col==index.col)
    {
        return YES;
    }
    return NO;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"%ld行%ld列", ToULong self.row, ToULong self.col];
}

@end

/**
 *  CFormCellView
 */

@implementation CFormCellView
{
    NSString *_reuseIdentifier;
    UIView *_selectedBackgroundView;
    UILabel *_textLable;
    UIImageView *_iconView;
    EFormBorderMask _normalBorderMask;
}

@synthesize reuseIdentifier = _reuseIdentifier;
@synthesize selectedBackgroundView = _selectedBackgroundView;
@synthesize textLable = _textLable;
@synthesize iconView = _iconView;

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithFrame:CGRectMake(0, 0, 40, 40)])
    {
        self.clipsToBounds = NO;
        self.opaque = NO;
        self.layer.masksToBounds = NO;
        _reuseIdentifier = [reuseIdentifier copy];
        self.borderSize = 1;
        self.borderColor = [UIColor colorWithHex:0xd2d8df];
        self.borderMask = EFormBorderLeft | EFormBorderTop | EFormBorderRight | EFormBorderBottom;
        self.selectable = YES;
        self.highlightable = YES;
        
        self.selectedBackgroundColor = [UIColor flatLightBlueColor];
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    [self setNeedsLayout];
    [self setNeedsDisplay];
}

- (void)setBorderMask:(EFormBorderMask)borderMask
{
    _borderMask = borderMask;
    _normalBorderMask = borderMask;
    [self setNeedsDisplay];
}

- (void)setBorderSize:(CGFloat)borderSize
{
    _borderSize = borderSize;
    [self setNeedsDisplay];
}

- (void)setBorderColor:(UIColor *)borderColor
{
    UIColor *tmp = [borderColor retain];
    [_borderColor release];
    _borderColor = tmp;
    
    [self setNeedsDisplay];
}

- (void)setSelected:(BOOL)selected
{
    _selected = selected;
    [self setNeedsDisplay];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor);
    CGContextFillRect(context, rect);
    
//    EFormBorderMask borderMask = self.selected == YES && self.highlightable == YES ? EFormBorderLeft|EFormBorderTop|EFormBorderBottom|EFormBorderRight : self.borderMask;
//    CGContextSetStrokeColorWithColor(context, self.selected == YES && self.highlightable == YES ? [UIColor colorWithHex:0xeec451].CGColor : self.borderColor.CGColor);
//    CGContextSetLineWidth(context, self.selected == YES && self.highlightable == YES ? 3 : self.borderSize);
    
    EFormBorderMask borderMask = self.borderMask;
    CGContextSetStrokeColorWithColor(context, self.borderColor.CGColor);
    CGContextSetLineWidth(context, self.borderSize);
    
    if (borderMask & EFormBorderLeft)
    {
        CGContextMoveToPoint(context, 0, self.height);
        CGContextAddLineToPoint(context, 0, 0);
    }
    if (borderMask & EFormBorderTop)
    {
        CGContextMoveToPoint(context, 0, 0);
        CGContextAddLineToPoint(context, self.width, 0);
    }
    if (borderMask & EFormBorderRight)
    {
        CGContextMoveToPoint(context, self.width, 0);
        CGContextAddLineToPoint(context, self.width, self.height);
    }
    if (borderMask & EFormBorderBottom)
    {
        CGContextMoveToPoint(context, self.width, self.height);
        CGContextAddLineToPoint(context, 0, self.height);
    }
    CGContextStrokePath(context);
}

- (UILabel *)textLable
{
    if (_textLable == nil)
    {
        _textLable = [[UILabel alloc] initWithFrame:CGRectZero];
        _textLable.backgroundColor = [UIColor clearColor];
        _textLable.numberOfLines = 0;
        _textLable.textAlignment = NSTextAlignmentLeft;
        _textLable.font = [UIFont systemFontOfSize:DEF_FORM_CELL_FONT_SIZE];
        _textLable.highlightedTextColor = [UIColor whiteColor];
        [self addSubview:_textLable];
    }
    return _textLable;
}

- (UIImageView *)iconView
{
    if (_iconView == nil)
    {
        _iconView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self addSubview:_iconView];
    }
    return _iconView;
}

- (UIView *)selectedBackgroundView
{
    if (_selectedBackgroundView == nil)
    {
        _selectedBackgroundView = [[UIImageView alloc] initWithFrame:self.bounds];
        ((UIImageView *)_selectedBackgroundView).image = [[UIImage imageNamed:@"gtv_cell_bg_selected"] resizeableCenterImage];
        _selectedBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self insertSubview:_selectedBackgroundView atIndex:0];
    }
    return _selectedBackgroundView;
}

- (void)setSelectedBackgroundView:(UIView *)selectedBackgroundView
{
    if (_selectedBackgroundView != nil)
    {
        [_selectedBackgroundView removeFromSuperview];
    }
    
    UIView *temp = [selectedBackgroundView retain];
    [_selectedBackgroundView release];
    _selectedBackgroundView = temp;
    if (_selectedBackgroundView != nil)
    {
        _selectedBackgroundView.alpha = 0.0;
        _selectedBackgroundView.frame = self.bounds;
        _selectedBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self insertSubview:_selectedBackgroundView atIndex:0];
    }
}

- (void)setSelectedState:(BOOL)bSelected animated:(BOOL)animated
{
    if (self.selectable == NO)
    {
        return;
    }
    if (_iconView != nil)
    {
        _iconView.highlighted = bSelected;
    }
    if (_textLable != nil)
    {
        _textLable.highlighted = bSelected;
    }
    if (bSelected == YES)
    {
        if (animated == NO)
        {
            self.selectedBackgroundView.alpha = 1.0;
        }
        else
        {
            self.selectedBackgroundView.alpha = 0.0;
            [UIView animateWithDuration:.3 animations:^{
                self.selectedBackgroundView.alpha = 1.0;
            } completion:^(BOOL finished) {
                
            }];
        }
    }
    else
    {
        if (animated == NO)
        {
            self.selectedBackgroundView.alpha = 0.0;
        }
        else
        {
            [UIView animateWithDuration:.3 animations:^{
                self.selectedBackgroundView.alpha = 0.0;
            } completion:^(BOOL finished) {
                
            }];
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    if (_iconView != nil)
    {
        CGSize imageSize = self.iconView.image.size;
        _iconView.frame = CGRectMake(_textLable == nil ? (self.width-imageSize.width)/2 : self.width-FORMVIEW_CELL_IMAGE_MARGIN-imageSize.width, (self.height-imageSize.height)/2, imageSize.width, imageSize.height);
    }
    if (_textLable != nil)
    {
        _textLable.frame = CGRectMake(FORMVIEW_CELL_MARGIN_X, FORMVIEW_CELL_MARGIN_Y, _iconView==nil ? self.width-2*FORMVIEW_CELL_MARGIN_X : self.iconView.left-2*FORMVIEW_CELL_MARGIN_X, self.height-2*FORMVIEW_CELL_MARGIN_Y);
    }
}

+ (CGSize)textLabelSizeWithCellSize:(CGSize)cellSize
{
    return [self textLabelSizeWithCellSize:cellSize iconSize:CGSizeZero];
}

+ (CGSize)textLabelSizeWithCellSize:(CGSize)cellSize iconSize:(CGSize)iconSize
{
    CGSize textLabelSize = CGSizeMake(iconSize.width>0 ? (cellSize.width-FORMVIEW_CELL_IMAGE_MARGIN-iconSize.width-2*FORMVIEW_CELL_MARGIN_X) : (cellSize.width-2*FORMVIEW_CELL_MARGIN_X),
                                      cellSize.height-2*FORMVIEW_CELL_MARGIN_Y);
    return textLabelSize;
}

+ (CGSize)cellSizeWithTextSize:(CGSize)textSize
{
    return [self cellSizeWithTextSize:textSize iconSize:CGSizeZero];
}

+ (CGSize)cellSizeWithTextSize:(CGSize)textSize iconSize:(CGSize)iconSize
{
    if (iconSize.width == 0)
    {
        return CGSizeMake(textSize.width+2*FORMVIEW_CELL_MARGIN_X, textSize.height+2*FORMVIEW_CELL_MARGIN_Y);
    }
    else
    {
        return CGSizeMake(textSize.width+FORMVIEW_CELL_IMAGE_MARGIN+iconSize.width+2*FORMVIEW_CELL_MARGIN_X, MAX(iconSize.height, textSize.height)+2*FORMVIEW_CELL_MARGIN_Y);
    }
}

- (void)dealloc
{
    [_textLable release];
    [_iconView release];
    [_borderColor release];
    [_selectedBackgroundView release];
    [_reuseIdentifier release];
    [super dealloc];
}

@end

@implementation CFormTextInputCellView
{
    UIView *_editFrameView;
}

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        _editFrameView = [[UIView alloc] initWithFrame:CGRectInset(self.bounds, 5, 5)];
        _editFrameView.backgroundColor = [UIColor clearColor];
        _editFrameView.layer.borderWidth = 1;
        _editFrameView.layer.borderColor = [UIColor flatLightGrayColor].CGColor;
        _editFrameView.layer.cornerRadius = 3;
        [self insertSubview:_editFrameView atIndex:0];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _editFrameView.frame = CGRectInset(self.bounds, 5, 5);
}

- (void)setSelected:(BOOL)selected
{
    [super setSelected:selected];
    _editFrameView.layer.borderColor = selected ? [UIColor colorWithHex:0x00AAFF].CGColor : [UIColor flatLightGrayColor].CGColor;
}

//- (void)drawRect:(CGRect)rect
//{
//    [super drawRect:rect];
//    if (self.selected == NO)
//    {
//        CGContextRef context = UIGraphicsGetCurrentContext();
//        CGContextSetLineWidth(context, 2);
//        CGContextSetStrokeColorWithColor(context, [UIColor flatBlueColor].CGColor);
//        CGContextMoveToPoint(context, 0, self.height-1);
//        CGContextAddLineToPoint(context, self.width, self.height-1);
//        CGContextStrokePath(context);
//    }
//}

@end


@implementation CFormLinkCellView

- (NSString *)text
{
    return self.textLable.text;
}

- (void)setText:(NSString *)text
{
    self.textLable.text = text;
    self.textLable.textColor = self.hasClicked == NO ? [UIColor colorWithHex:0x1d529c] : [UIColor grayColor];
}

- (void)setHasClicked:(BOOL)hasClicked
{
    if (_hasClicked == hasClicked)  {
        return;
    }
    _hasClicked = hasClicked;
    self.text = self.text;
}

@end

@implementation CFormSelectorCellView

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier])
    {
        [self updateImage];
    }
    return self;
}

- (void)setUnique:(BOOL)unique
{
    if (_unique == unique)
    {
        return;
    }
    _unique = unique;
    [self updateImage];
}

- (void)setChosed:(BOOL)chosed
{
    if (_chosed == chosed)
    {
        return;
    }
    _chosed = chosed;
    [self updateImage];
}

- (void)updateImage
{
    self.iconView.image = [UIImage imageNamed:self.unique ? (self.chosed ? @"select_unique" : @"unselect_unique") : (self.chosed ? @"select_multiple" : @"unselect_multiple")];
}

@end

@implementation CFormImageCellView
{
    UIView *maskView;
    UIImageView *_imageView;
}

@synthesize imageView = _imageView;

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier])
    {
        maskView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
        [self addSubview:maskView];
        maskView.clipsToBounds = YES;
        [self addObserver:self forKeyPath:@"self.imageView.image" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];
    if (self.superview != nil)
    {
        [self adjustImage];
    }
}

- (UIImageView *)imageView
{
    if (_imageView == nil)
    {
        _imageView = [[UIImageView alloc] initWithFrame:maskView.bounds];
        [maskView addSubview:_imageView];
    }
    return _imageView;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"self.imageView.image"])
    {
        [self adjustImage];
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    maskView.frame = CGRectInset(self.bounds, 2, 2);
    [self adjustImage];
}

- (void)adjustImage
{
    if (maskView.width > 0 && self.imageView.image != nil)
    {
        CGFloat w, h;
        CGFloat rateW = self.imageView.image.size.width / maskView.width;
        CGFloat rateH = self.imageView.image.size.height / maskView.height;
        CGFloat rateScale = rateW < rateH ? 1.0 / rateW : 1.0 / rateH;
        w = rateScale * self.imageView.image.size.width;
        h = rateScale * self.imageView.image.size.height;
        self.imageView.frame = CGRectMake(w > maskView.width ? (maskView.width - w) / 2 : 0, h > maskView.height ? (maskView.height - h) / 2 : 0, w, h);
    }
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"self.imageView.image" context:nil];
    [_imageView release];
    [super dealloc];
}

@end

@implementation CFormDropDownCellView

+ (CGSize)textLabelSizeWithCellSize:(CGSize)cellSize
{
    return [self textLabelSizeWithCellSize:cellSize iconSize:[UIImage imageNamed:@"table_dropdown"].size];
}

+ (CGSize)cellSizeWithTextSize:(CGSize)textSize
{
    return [self cellSizeWithTextSize:textSize iconSize:[UIImage imageNamed:@"table_dropdown"].size];
}

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier])
    {
        self.iconView.image = [UIImage imageNamed:@"table_dropdown"];
    }
    return self;
}

@end

@implementation CFormCallCellView

+ (CGSize)textLabelSizeWithCellSize:(CGSize)cellSize
{
    return [self textLabelSizeWithCellSize:cellSize iconSize:[UIImage imageNamed:@"ab_phone_normal"].size];
}

+ (CGSize)cellSizeWithTextSize:(CGSize)textSize
{
    return [self cellSizeWithTextSize:textSize iconSize:[UIImage imageNamed:@"ab_phone_normal"].size];
}

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier])
    {
        self.iconView.highlightedImage = [UIImage imageNamed:@"ab_phone_normal"];
        self.iconView.image = [UIImage imageNamed:@"ab_phone_selected"];
    }
    return self;
}

@end

@implementation CFormMarkCellView
{
    UILabel *markLable;
}

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier])
    {
        markLable = [[UILabel alloc] initWithFrame:CGRectZero];
        markLable.backgroundColor = [UIColor clearColor];
        markLable.textAlignment = NSTextAlignmentLeft;
        markLable.font = [UIFont systemFontOfSize:15];
        [markLable setTextColor:[UIColor redColor]];
        markLable.numberOfLines = 1;
        markLable.text = @"*";
        
        [self addSubview:markLable];
    }
    return self;
}

- (void)hideMark:(BOOL)bShow
{
    [markLable setHidden:bShow];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGSize textSize = [self.textLable.text stringSizeWithFont:self.textLable.font forConstrainSize:self.textLable.size];
    [self.textLable setFrame:CGRectMake((self.width-textSize.width)/2, (self.height-textSize.height)/2, textSize.width, textSize.height)];
    [markLable setFrame:CGRectMake(self.textLable.right, self.center.y, FORMVIEW_CELL_MARGIN_Y, FORMVIEW_CELL_MARGIN_Y)];
}

@end